package com.tencent.iov.cowin.befsale.clue.service.cus.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.CustomerExtAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.DealerCustomerAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.assembler.OemCustomerAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.ClueIntentionGradeDataRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.QueryCustomerRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.UpdateCustomerRequest;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.CustomerResponse;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.CustomerBehavior;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.CustomerExt;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.DealerCustomer;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.OemCustomer;
import com.tencent.iov.cowin.befsale.clue.repository.cus.OemCustomerManager;
import com.tencent.iov.cowin.befsale.clue.service.cus.*;
import com.tencent.iov.cowin.befsale.clue.service.cus.*;
import com.tencent.iov.cowin.befsale.clue.value.enums.CustomerExtCustomerTypeEnum;
import com.tencent.iov.cowin.befsale.clue.value.enums.CustomerTypeEnum;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.PageRequest;
import com.software.boot.common.model.dao.PageResponse;
import com.software.boot.common.util.BeanUtil;
import com.software.boot.common.util.EmptyUtils;
import com.software.boot.common.util.ValidateUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @Describe: 总部客户表主表+客户好友关联表_Service实现层
 * @author: xiamu
 * @created: 2021-12-21 18:37:23
 * @version: 1.0
 */
@Service
public class OemCustomerServiceImpl implements OemCustomerService {

    @Autowired
    private OemCustomerManager oemCustomerManager;

    @Autowired
    private DealerCustomerService dealerCustomerService;
    @Autowired
    private CustomerExtService customerExtService;
    @Autowired
    private CustomerBehaviorService customerBehaviorService;
    @Autowired
    private CustomerService customerService;

    @Override
    public CustomerResponse getDetailById(Long id) {
        //验证请求参数
        ValidateUtils.checkLongGTZero(id, "ID不能为空或小于0");

        // 处理业务
        OemCustomer oemCustomer = oemCustomerManager.getDetailById(id);
        if (EmptyUtils.isEmpty(oemCustomer)) {
            return null;
        }
        //添加标签信息
        CustomerExt queryCustomerExt = new CustomerExt();
        queryCustomerExt.setCusId(oemCustomer.getId());
        queryCustomerExt.setCustomerType(CustomerExtCustomerTypeEnum.OEM_CUSTOMER.getCode());
        CustomerExt customerExt = customerExtService.getOneByParam(queryCustomerExt);

        CustomerResponse customerResponse = BeanUtil.copy(oemCustomer, CustomerResponse.class);

        if (EmptyUtils.isNotEmpty(customerExt)) {
            OemCustomerAssembler.initCustomerResponse(customerResponse, customerExt);
        }

        //基本标签的拼接 + 渠道与活动
        customerResponse.setCustomerCodeStr(customerService.getClueCustomerTagStr(customerResponse));

        //添加行为标签信息
        CustomerBehavior queryBehavior = new CustomerBehavior();
        queryBehavior.setCusType(CustomerTypeEnum.CUSTOMER_TYPE_OEM.getCode());
        queryBehavior.setOemCusId(oemCustomer.getId());
        queryBehavior.setCorpId(oemCustomer.getCorpId());
        queryBehavior.setTenantId(oemCustomer.getTenantId());
        CustomerBehavior customerBehavior = customerBehaviorService.statisticalByCusId(queryBehavior);
        if (EmptyUtils.isNotEmpty(customerBehavior)) {
            customerResponse.setCustomerBehavior(JSON.toJSONString(customerBehavior));
        }
        return customerResponse;
    }

    /**
     * 单条数据插入OemCustomer
     *
     * @param request
     * @return 插入的条数
     */
    @Override
    public int insert(OemCustomer request) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = oemCustomerManager.insert(request);
        /** 3 封装返回值 */
        return count;
    }

    /**
     * 批量插入OemCustomer
     *
     * @param requests
     * @return 批量插入的条数
     */
    @Override
    public int insertBatch(List<OemCustomer> requests) {
        /** 1 验证请求参数 */
        /** 2 处理业务 */
        int count = oemCustomerManager.insertBatch(requests);
        /** 3 封装返回值 */
        return count;
    }

    @Override
    public int update(UpdateCustomerRequest request) {
        //验证请求参数
        ValidateUtils.checkObjNull(request, "请求参数为null");
        if (EmptyUtils.isEmpty(request.getId()) && EmptyUtils.isEmpty(request.getIds())) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_EMPTY, "总部客户主键ID不可以为null");
        }
        //处理业务
        OemCustomer oemCustomer = BeanUtil.copy(request, OemCustomer.class);
        return oemCustomerManager.update(oemCustomer);
    }

    @Override
    public int updateById(OemCustomer oemCustomer) {
        return oemCustomerManager.update(oemCustomer);
    }

    /**
     * 通过ID删除数据
     *
     * @param request
     * @return 删除的条数
     */
    @Override
    public int delete(OemCustomer request) {
        Long id = request.getId();
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(id, "请求参数不能为空");
        ValidateUtils.checkIntNotNullAndGTZero(id.intValue(), "ID不能为空或小于0");
        /** 2 处理业务 */
        OemCustomer oemCustomer = new OemCustomer();
        oemCustomer.setId(id);
//		oemCustomer.setDelete(DeleteEnum.DETELED.getCode());
        int count = oemCustomerManager.update(oemCustomer);
        /** 3 返回对象 */
        return count;
    }

    /**
     * 根据条件查询对象对象list列表
     *
     * @param request
     * @return 查询结果
     */
    @Override
    public List<CustomerResponse> getListByParam(QueryCustomerRequest request) {
        /** 1 验证请求参数 */
        //可以设置排序
        //转化数据
        OemCustomer oemCustomer = DealerCustomerAssembler.transformVOToPO(request, OemCustomer.class);
        /** 2 处理业务 */
        List<OemCustomer> queryList = oemCustomerManager.getListByParam(oemCustomer);
        /** 3 返回结果 */
        if (CollectionUtils.isNotEmpty(queryList)) {
            return BeanUtil.copyByList(queryList, CustomerResponse.class);
        }
        return new ArrayList<>();
    }

    /**
     * 根据条件查询对象list记录
     *
     * @param request
     * @return 分页对象
     */
    @Override
    public PageResponse<OemCustomer> getPageByParam(PageRequest<OemCustomer> request) {
        /** 1 验证请求参数 */
        ValidateUtils.checkObjNull(request, "请求参数不能为空");
        //可以设置排序 query.orderByCreatedTime(true);
        /** 2 处理业务 */
        RowBounds rowBounds = new RowBounds(request.getPageNum(), request.getPageSize());
        Page<OemCustomer> queryPageList = oemCustomerManager.getPageByParam(request.getParamData(), rowBounds);
        PageResponse<OemCustomer> pageResponse = new PageResponse<>();
        pageResponse.converPageResponse(pageResponse, queryPageList, request);
        pageResponse.setDataList(BeanUtil.copyByList(queryPageList.getResult(), OemCustomer.class));
        /** 3 返回结果 */
        return pageResponse;
    }

    /**
     * 根据条件查询单个对象
     *
     * @param request
     * @return
     */
    @Override
    public CustomerResponse getOneByParam(OemCustomer request) {
        OemCustomer oemCustomer = oemCustomerManager.getOneByParam(request);
        return OemCustomerAssembler.transformVOToPO(oemCustomer, CustomerResponse.class);
    }

    /**
     * @param phone
     * @return true :存在活跃线索  false 不存在活跃线索
     */
    @Override
    public Boolean checkCustomerPhone(String phone, String dealerId,String tenantId,String corpId) {
        OemCustomer request = new OemCustomer();
        request.setPhone(phone);
        request.setCorpId(corpId);
        request.setTenantId(tenantId);
        //经销商id为空则查询总部客户
        if (StringUtils.isEmpty(dealerId)||"0".equals(dealerId)) {
            List<OemCustomer> oemCustomerList = oemCustomerManager.checkOemCustomerPhone(request);
            if (CollectionUtils.isNotEmpty(oemCustomerList)) {
                return true;
            }
        } else {
            //经销商id不为空则查询经销商客户
            DealerCustomer dealerCustomer = new DealerCustomer();
            dealerCustomer.setDealerId(dealerId);
            dealerCustomer.setPhone(phone);
            dealerCustomer.setCorpId(corpId);
            dealerCustomer.setTenantId(tenantId);
            List<DealerCustomer> dealerCustomerList = dealerCustomerService.checkDealerCustomerPhone(dealerCustomer);
            if (CollectionUtils.isNotEmpty(dealerCustomerList)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public Boolean updateOemCustomer(UpdateCustomerRequest updateCustomer) {
        ValidateUtils.checkObjNull(updateCustomer, "参数信息为null");
        ValidateUtils.checkLongGTZero(updateCustomer.getId(), "总部客户主键Id参数为null");
        OemCustomer existOemCustomer = oemCustomerManager.getDetailById(updateCustomer.getId());
        ValidateUtils.checkObjNull(existOemCustomer, "总部客户信息不存在");
        updateCustomer = OemCustomerAssembler.initUpdateOemCustomerRequest(updateCustomer);
        String followEmpId = existOemCustomer.getFollowEmpId().toString();
        if (EmptyUtils.isNotEmpty(existOemCustomer.getFollowEmpId()) && !followEmpId.equals(updateCustomer.getUpdatedBy())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "请操作自己跟进的线索信息");
        }
        //更新客户基本信息 bef_oem_customer
        OemCustomer updateOemCustomer = OemCustomerAssembler.transformVOToPO(updateCustomer, OemCustomer.class);
        if (EmptyUtils.isNotEmpty(updateOemCustomer)) {
            int updateOemResult = oemCustomerManager.update(updateOemCustomer);
            if (updateOemResult <= 0) {
                throw new BusinessException(NEError.BUSINESS_ERROR, "更新总部客户信息失败");
            }
        }

        //保存客户标签信息 bef_customer_ext
        CustomerExt customerExt = CustomerExtAssembler.transformVOToPO(updateCustomer, CustomerExt.class);
        if (EmptyUtils.isEmpty(customerExt)) {
            return true;
        }
        customerExt.setCusId(updateCustomer.getId());
        customerExt.setCustomerType(CustomerTypeEnum.CUSTOMER_TYPE_OEM.getCode());
        Long extId = customerExtService.insertOrUpdateCustomerExt(customerExt);
        if (EmptyUtils.isEmpty(extId) || extId <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "总部客户扩展信息处理失败");
        }
        return true;
    }

    @Override
    public String checkOneId(String oneId, String dealerId, Long followEmpId,String tenantId,String corpId) {
        String resultStr = null;
        //经销商id为空则查询总部客户
        if (StringUtils.isEmpty(dealerId)||"0".equals(dealerId)) {
            OemCustomer request = new OemCustomer();
            request.setOneId(oneId);
            request.setCorpId(corpId);
            request.setTenantId(tenantId);
            request.setFollowEmpId(followEmpId);
            List<OemCustomer> oemCustomerList = oemCustomerManager.checkOemCustomerOneId(request);
            if (CollectionUtils.isNotEmpty(oemCustomerList) && oemCustomerList.size() > 0) {
                OemCustomer resultOemCustomer = oemCustomerList.get(0);
                if(resultOemCustomer.getFollowEmpId()==null||resultOemCustomer.getFollowEmpId()==-1||
                        followEmpId==null||followEmpId==-1){
                    return resultStr;
                }else if(String.valueOf(followEmpId).equals(String.valueOf(resultOemCustomer.getFollowEmpId()))){
                    return resultStr;
                }else {
                    resultStr = "跟进人empId为:" + resultOemCustomer.getFollowEmpId() + ",跟进人empName为:" + resultOemCustomer.getFollowEmpName();
                    return resultStr;
                }
            }
        } else {
            //经销商id不为空则查询经销商客户
            DealerCustomer dealerCustomer = new DealerCustomer();
            dealerCustomer.setOneId(oneId);
            dealerCustomer.setCorpId(corpId);
            dealerCustomer.setTenantId(tenantId);
            dealerCustomer.setFollowEmpId(followEmpId);
            dealerCustomer.setDealerId(dealerId);
            List<DealerCustomer> dealerCustomerList = dealerCustomerService.checkDealerCustomerOneId(dealerCustomer);
            if (CollectionUtils.isNotEmpty(dealerCustomerList) && dealerCustomerList.size() > 0) {
                DealerCustomer resultDealerCustomer = dealerCustomerList.get(0);
                if(resultDealerCustomer.getFollowEmpId()==null||resultDealerCustomer.getFollowEmpId()==-1||
                        followEmpId==null||followEmpId==-1){
                    return resultStr;
                }else if(String.valueOf(followEmpId).equals(String.valueOf(resultDealerCustomer.getFollowEmpId()))){
                    return resultStr;
                }else {
                    resultStr = "跟进人empId为:" + resultDealerCustomer.getFollowEmpId() + ",跟进人empName为:" + resultDealerCustomer.getFollowEmpName();
                    return resultStr;
                }
            }
        }
        return resultStr;
    }

    /**
     * 获取客户转线索的数量
     * add by zly
     * 2022-01-15
     * @param clueDataRequest
     * @return
     */
    @Override
    public Long getEmpBindCount(ClueIntentionGradeDataRequest clueDataRequest) {
        return oemCustomerManager.getEmpBindCount(clueDataRequest);
    }


}
